<script>
import {handleSuccess, handleError} from "@/util/request";
export default {
  name: "HomePage",
  data() {
    return {
      user:{}
    }
  },
  mounted() {
    try {
      this.user = JSON.parse(localStorage.getItem('user'))
      if (!this.user) {
        this.$router.replace('/login')
      }
    }catch (e) {
      this.$router.replace('/login')
    }
  },
	methods: {
		logout() {
			this.$http.post('/user/logout')
				.then((result) => {
					// 将result交给handleSuccess进行统一业务异常处理
					//待修改 并拿到handleSuccess返回的对象, 我们在handleSuccess中返回的是result中的第三层对象, 即后端响应的数据
					//待修改 这里的第三层对象是user对象, 定义一个变量user接收
					const logoutResult = handleSuccess(result);
					// 如果user不为空说明登录业务成功, js中判空可以直接 if(变量名)
					console.log(logoutResult);
					if (logoutResult) {
					console.log("Succ");
					// 将user存储到localStorage中
					localStorage.removeItem('user');
					// 跳转路由到主页
					location.reload();
				}
			})
			.catch((error)=> {
				// 将error交给handleError进行统一HTTP请求异常处理
				handleError(error)
			});
		}
	}
}
</script>

<template>
  <el-container>
    <el-aside width="280px" style="height: 100vh;">
      <el-menu router style="height: 100vh;" class="el-menu-vertical-demo" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
        <el-submenu index="1" v-if="user.role == '管理员'">
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>物资管理</span>
          </template>
          <el-menu-item index="/material/save">添加物资</el-menu-item>
          <el-menu-item index="/material/page">物资查询</el-menu-item>
        </el-submenu>
        <el-submenu index="2" v-if="user.role == '管理员'">
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>库存管理</span>
          </template>
          <el-menu-item index="/inventory/change">出入库</el-menu-item>
		  <el-menu-item index="/inventory/check">出入库记录</el-menu-item>
        </el-submenu>
		<el-menu-item>
		  <el-button type="danger" style="width:100%" @click="logout">登出</el-button>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <el-main style="height: 100vh;">
      <router-view/>
    </el-main>
  </el-container>
</template>

<style scoped>

</style>
